<template>
  <div class="manage-file">
    <div v-show="editVisible == false">
      <div class="path_nav">
        <div v-for="(item, index) in pathArr" :key="index">
          <el-link type="primary" style="cursor: pointer" @click="toPath(item)">{{
            item.split("/")[0]
          }}</el-link>
          <span class="gang">/</span>
        </div>

        <input
          v-show="wantAdd"
          ref="myinput"
          v-model="addPath"
          type="text"
          class="native_input"
          @blur="blur"
          @keyup.enter="blur"
        />
        <i v-show="!wantAdd" class="el-icon-folder-add" @click="showInput"></i>
      </div>
      <el-input
        v-model="projectName"
        clearable
        placeholder="Search Name..."
        prefix-icon="el-icon-search"
        @input="search"
      >
      </el-input>

      <el-upload
        :http-request="httpRequest"
        :file-list="uploadList"
        :limit="1"
        :disabled = enable_upload
        drag
        class="upload-demo"
        action="https://jsonplaceholder.typicode.com/posts/"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <el-progress v-if="progressPercent > 0" :stroke-width="2" :percentage="progressPercent"></el-progress>
      <!-- 文件可拖拽 -->
      <div class="tree-box">
        <div class="tree-header tree-line">
          <p class="header-cell line-name">Name</p>
          <p class="header-cell line-size">size</p>
          <p class="header-cell line-time">Last Modified</p>
          <p class="header-cell line-active">Action</p>
        </div>
        <el-tree
          :data="fileList"
          node-key="id"
          draggable
          @node-drop="handleDrop"
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
          :expand-on-click-node="false">
          <div class="tree-line tree-tr" slot-scope="{ node, data }">
            <div class="tr-cell line-name">
              <div class="circle" :class="data.is_dir?'dir':''">
                <i v-if="data.is_dir" class="el-icon-folder" @click="toDir(data.file_name, data.is_dir)"></i>
                <i v-else class="el-icon-document"></i>
              </div>
              <el-input
                v-if="isEdit == data.path"
                v-model="cueFileName"
                placeholder="请输入内容"
                autofocus
                @change="renameComplete(data)"
                @blur="() => {isEdit = -1}">
              </el-input>
              <span class="file-name" v-else @click="toDir(data.file_name, data.is_dir)">{{ data.file_name }}</span>
            </div>
            <p class="tr-cell line-size">{{ data.size | getSize }}</p>
            <p class="tr-cell line-time">{{ data.last_modified }}</p>
            <div class="tr-cell line-active">
              <el-popconfirm v-show="!isCICD(data.path)"
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除吗？"
                @onConfirm="handleDelete(data)"
              >
                <el-button
                  slot="reference"
                  :disabled="data.path == downloadPathName"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  size="mini"
                  />
              </el-popconfirm>
              <el-button
                v-if="data.is_dir == false"
                :disabled="data.path == downloadPathName"
                type="success"
                icon="el-icon-download"
                size="mini"
                circle
                style="margin-left: 10px"
                @click="download(data)"
                />
              <el-button
                v-if="showEdit(data)"
                :disabled="data.path == downloadPathName"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
                style="margin-left: 10px"
                @click="edit(data)"
                />
              <el-button
                v-if="data.is_dir == false"
                type="info"
                icon="el-icon-edit-outline"
                size="mini"
                circle
                @click="rename(data)"
                />
            </div>
          </div>
        </el-tree>
      </div>
    </div>
    <edit-file :edit-py-path="editPyPath" :edit-visible.sync="editVisible" />
  </div>
</template>
<script>
import axios from "axios";
import editFile from "./edit-file";

export default {
  name: "ManageFile",
  components: {
    editFile
    // draggable
  },
  data() {
    return {
      editVisible: false,
      editPyPath: "",
      addPath: "",
      path: "",
      file_name: "",
      target_folder: "",
      source_file: "",
      wantAdd: false,
      usedSize: 73.6,
      projectName: "",
      usePercent: 20,
      fileList: [],
      uploadList: [],
      totalList: [],
      downloadPathName: "",
      pathArr: [this.$route.query.project_id + "/"],
      isEdit: -1,
      cueFileName: '',
      progressPercent: 0,
      enable_upload: false
    };
  },

  watch: {
    pathArr: {
      deep: true,
      handler(newVal) {
        const joined = newVal.join(""); // 拼接成字符串
        const parts = joined.split('/');
        this.enable_upload = parts[1] === 'CICD';
      }
    }
  },
  created() {
    this.initData();
  },
  mounted() { },
  computed: {
    customColor() {
      if (this.usePercent < 50) {
        return "#67c23a";
      } else if (this.usePercent >= 50 && this.usePercent < 80) {
        return "#e6a23c";
      } else {
        return "#f56c6c";
      }
    },
    showEdit(row) {
      return row => {
        let arr = row.file_name.split(".");
        let whiteList = ['py', 'properties']
        let type = arr[arr.length - 1]
        if (row.is_dir == false && whiteList.includes(type)) return true;
        else return false;
      };
    }
  },
  filters: {
    getSize(size) {
      if (!size) return "";
      if (size <= 1024) {
        return size + " Byte";
      } else if (size > 1024 && size <= 1024 * 1024) {
        return (size / 1024).toFixed(2) + " KB";
      } else if (size > 1024 * 1024 && size <= 1024 * 1024 * 1024) {
        return (size / 1024 / 1024).toFixed(2) + " MB";
      } else {
        return (size / 1024 / 1024 / 1024).toFixed(2) + " GB";
      }
    },
  },
  methods: {
    isCICD(path) {
      const parts = path.split('/');
      return parts[1] === 'CICD' && (path.match(/\//g) || []).length<4; // 判断第一个 '/' 后的部分是不是 'CICD'
    },
    // 可放置
    allowDrop(draggingNode, dropNode, type) {
      return dropNode.data.is_dir
    },
    // 可拖拽
    allowDrag(node) {
      return !node.data.is_dir 
    },
    // 文件放置文件夹中
    handleDrop(draggingNode, dropNode, dropType, ev) {
      let currRow = draggingNode.data
      let dopRow = dropNode.data
      this.$http.file.renameFile({
        source_file: currRow.path,
        target_folder: dopRow.path,
        file_name: currRow.file_name
      }).then(res => {
        this.$message.success(`文件${currRow.file_name}已放入文件夹${dopRow.file_name}`)
      })
    },
    edit(row) {
      this.editVisible = true;
      this.editPyPath = row.path;
    },
    showInput() {
      this.wantAdd = true;
      this.$nextTick(() => {
        this.$refs.myinput.focus();
      });
    },
    initData() {
      this.$http.managefiles.getFilesByPath({ path: this.pathArr.join("") }).then(res => {
        this.fileList = res;
        this.totalList = res;
      });
    },
    download(row) {
      this.downloadPathName = row.path;
      this.$message({
        message: "文件下载中",
        type: "info",
        duration: 500
      });
      this.$http.managefiles.downLoadFile({ path: row.path }).then(res => {
        const blob = new Blob([res], { type: "application/octet-stream" });
        let dom = document.createElement("a");
        let url = window.URL.createObjectURL(blob);
        dom.href = url;
        dom.download = row.file_name;
        dom.style.display = "none";
        document.body.appendChild(dom);
        dom.click();
        dom.parentNode.removeChild(dom);
        window.URL.revokeObjectURL(url);
        this.downloadPathName = "";
        this.$message({
          message: "文件下载完成",
          type: "success"
        });
      });
    },
    handleDelete(row) {
      this.$http.managefiles.delFile({ path: row.path }).then(res => {
        this.$message({
          message: "删除成功",
          type: "success"
        });
        this.initData();
      });
    },
    rename(row) {
      this.isEdit = row.path;
      this.cueFileName = row.file_name
    },
    renameComplete(row) {
      this.isEdit = -1
      let pathTarget = row.path.toString();
      this.$http.file.renameFile({
        source_file: row.path,
        target_folder: pathTarget.substring(0,(pathTarget.lastIndexOf("/"))+1 ),
        file_name: this.cueFileName
      })
      .then(res => {
        this.initData();
      })
    },
    search() {
      this.fileList = this.totalList.filter(item => {
        return item.file_name.indexOf(this.projectName) > -1;
      });
    },
    httpRequest(data) {
      let token = this.$cookies.get("token")
      let fd = new FormData();
      fd.append("file", data.file)
      fd.append("size", data.file.size)
      fd.append("path", this.pathArr.join(""));
      axios({
        method: "post",
        url: "/api/idata/files/upload",
        headers: {
          "Content-Type": "multipart/form-data",
          "Authorization": token
        },
        data: fd,
        onUploadProgress: (progressEvent) => {
          this.progressPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(2))
        }
      }).then(res => {
        this.$message({
          message: "文件上传成功",
          type: "success"
        });
        this.uploadList = []
        this.progressPercent = 0
        this.initData();
      });
    },
    handleSelect(row) {
      this.pathArr.push(row.file_name);
      this.initData();
    },
    toPath(path) {
      let index = this.pathArr.findIndex(item => item == path);
      this.pathArr = this.pathArr.slice(0, index + 1);
      this.initData();
    },
    blur() {
      if (this.addPath.trim() == "") {
        this.addPath = "";
        this.wantAdd = false;
      } else {
        this.pathArr.push(this.addPath.trim() + "/");
        this.addPath = "";
        this.wantAdd = false;
        this.initData();
      }
    },
    // 点击表格左边 icon 进入文件夹
    toDir(path, is_dir){
      if(is_dir) {
        this.pathArr.push(path)
        this.initData();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.manage-file {
  /* margin-top: 10px; */
  height: 100%;
  .upload-demo{
    width: 400px;
  }
  .path_nav {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    .native_input {
      border: none;
      width: 80px;
      color: #46a5e0;
      font-size: 16px;
      margin-left: 5px;
    }
    .gang {
      font-size: 18px;
      color: #a090ab;
      vertical-align: middle;
    }
    .el-link {
      font-size: 16px !important;
      margin-left: 4px;
      margin-right: 3px;
      color: #46a5e0;
    }
    .el-icon-folder-add {
      font-weight: 700;
      font-size: 20px;
      cursor: pointer;
      color: #46a5e0;
      margin-left: 5px;
    }
  }
  .progress_text {
    color: #ababaa;
    margin-top: 5px;
    font-size: 15px;
    margin-bottom: 10px;
  }
  .circle {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background-color: #409EFF;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 15px;
    margin-right: 15px;
    &.dir{
      background-color: #E6A23C;
    }
    .el-icon-folder{
      cursor: pointer;
    }
  }
  .table_name {
    display: flex;
    align-items: center;
  }
  .point {
    font-weight: 700;
    color: #a3a3a3;
    font-size: 20px;
    cursor: pointer;
  }
  .tree-box{
    padding: 20px 0;
  }
  .tree-header{
    height: 50px;
    background: #f8f8f9;
    padding: 0 10px;
    box-sizing: border-box;
    .header-cell{
      color: #515a6e;
      font-size: 14px;
      font-weight: 500;
    }
  }
  .tree-tr{
    height: 50px;
    font-size: 15px;
  }
  .tree-line{
    width: 100%;
    display: flex;
    .line-name{
      width: 30%;
      display: flex;
      .file-name{
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .line-size{
      width: 20%
    }
    .line-time{
      width: 25%
    }
    .line-active{
      width: 25%
    }
    .tr-cell{
      &.line-name{
        width: calc(30% - 14px);
        transform: translateX(-14px);
        display: flex;
        align-items: center;
      }
      &.line-active{
        display: flex;
        align-items: center;
      }
    }
  }
}
/deep/.el-table__header-wrapper .el-table__header th {
  background-color: #f8f8f9;
  color: #515a6e;
  font-size: 14px;
  font-weight: 500;
}
/deep/.cell {
  display: flex;
  align-items: center;
}
/deep/.el-tree-node__content{
  height: 55px;
  border-bottom: 1px solid #f8f8f9;
}
/deep/ .el-upload-dragger{
  margin-top: 20px;
  width: calc(100vw - 300px);
}
</style>
